<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AG-UI Express服务</title>
</head>

<body>
    <p>AG-UI Express服务已启动</p>
    <div id="awp">
        <ul id="messageList"></ul>
        <input type="text" id="messageInput"><button onClick="sendMessage()">发送</button>
    </div>
    <script>
        async function fetchSSE(url, question, onMessage) {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    token: '11111',
                },
                body: JSON.stringify(question)
            });
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            while (true) {
                const {
                    done,
                    value
                } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, {
                    stream: true
                });

                const lines = buffer.split('\n');
                buffer = lines.pop(); // 保留未完整的一行

                for (const line of lines) {
                    if (line.startsWith('data:')) {
                        const data = line.slice(5).trim();
                        if (data) {
                            onMessage({
                                data
                            });
                        }
                    }
                }
            }

            if (buffer.length > 0) {
                const data = buffer.slice(5).trim();
                if (data) {
                    onMessage({
                        data
                    });
                }
            }
        }

        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();
            if (message) {
                messageInput.value = '';
                const id = Math.random() + '';
                // 发送消息到服务器
                fetchSSE('/awp', {
                    threadId: id,
                    runId: id,
                    messages: {
                        role: 'user',
                        content: message,
                    }
                }, (event) => {
                    console.log('Received SSE event:', event);
                    const data = JSON.parse(event.data);
                    
                    if (data.type === 'TEXT_MESSAGE_CONTENT') {
                        const messageItem = document.createElement('li');
                        messageItem.innerHTML += data.delta;
                        document.getElementById('messageList').appendChild(messageItem);
                    }
                })
            }
        }
    </script>
</body>

</html>